﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using TableProto;

public class StartPanel : SingletonBaseWindow<StartPanel>
{

    public TotalGallayImageData dats;

    public Animator _StartPanel;

    public HUITimerScript _Panel_timer { get; set; }

    public Transform _Panel_powerRemain { get; set; }

    public Transform _Panel_block { get; set; }

    public Text _text_PowerNum { get; set; }

    public Text _text_PhotoAmount { get; set; }

    public Transform _PhotoAmount { get; set; }

    public Button _Btn_back { get; set; }

    public Button _Btn_gallary { get; set; }

    public Button _Btn_start { get; set; }

    public Button _Btn_PowerShow { get; set; }

    public Button _Btn_Free_Power { get; set; }

    private Text Text_Free;

    public Transform _HandTip { get; set; }

    private int CountdownWithReset { get { return 60 * 60 * 24; } }

    private Dictionary<uint, MainItemInfo> dict;

    private MainItemInfo m_currentInfo;

    bool isNewPhotoAdd;

    Text _text_state;

    Transform _trans_textRemove;

    EarthMono earth;

    bool _isTravelStart;

    bool _isTravelPhotoReady;

    bool _isFlayAnimateFinished;

    bool _isOnGoumai;
    float _travelTimer;
    private int timeSeq;
    


    protected override void AddListeners()
    {
        base.AddListeners();
        _Btn_back.onClick.AddListener(OnBackBtnClicked);
        _Btn_gallary.onClick.AddListener(OnGallayBtnClicked);
        _Btn_start.onClick.AddListener(OnStartClicked);
        _Btn_PowerShow.onClick.AddListener(OnPowerShowPanelBtnClicked);
        _Btn_Free_Power.onClick.AddListener(OnFreePowerBtnClicked);

        EventBus.Instance.AddEventHandler(EventID.ON_EXPRESS_DATA_INIT_FINISHED, OnRefresh);
    }

    protected override void RemoveListensers()
    {
        base.RemoveListensers();
        _Btn_back.onClick.RemoveListener(OnBackBtnClicked);
        _Btn_gallary.onClick.RemoveListener(OnGallayBtnClicked);
        _Btn_start.onClick.RemoveListener(OnStartClicked);
        _Btn_PowerShow.onClick.RemoveListener(OnPowerShowPanelBtnClicked);
        _Btn_Free_Power.onClick.RemoveListener(OnFreePowerBtnClicked);

        EventBus.Instance.RemoveEventHandler(EventID.ON_EXPRESS_DATA_INIT_FINISHED, OnRefresh);
    }

    protected override void OnOpen(params object[] paramArray)
    {
        base.OnOpen(paramArray);

        _Panel_timer.Initialize(null);

        gameObject.SetActive(true);

        _Panel_block.SetActive(false);

        AdsControl();

        dict = TableProtoLoader.MainItemInfoDict;

        //ui滑入
        ExpressController.Instance.GetUIAnimatorEx(WinNames.StartPanel).CrossFade(eExpressUIAnimState.StartPanelIn.ToString(), ExpressConsts.dur_crossfade_openUI);

    }

    protected override void OnClose()
    {
        base.OnClose();
        TimerManager.Instance.RemoveTimer(AdsCountDown);
        EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, ReflashAds);
    }

    #region ads
    int ads_num;
    private void AdsControl()
    {
        EventBus.Instance.AddEventHandler<string>(EventID.ADS_DONE_CALLBACK, ReflashAds);
        this.Text_Free = this._Btn_Free_Power.transform.Find("Text_State").GetComponent<Text>();
        ReflashAds(AdsNameConst.Ads_Express.Name);
    }

    private void ReflashAds(string adsName)
    {
        if (adsName != AdsNameConst.Ads_Express.Name)
            return;
        if (AdsManager.Instance.CanShowNumAds(AdsNameConst.Ads_Express))
        {
            this._Btn_Free_Power.gameObject.SetActive(true);
            ads_num = AdsManager.Instance.AdsCoolTime(AdsNameConst.Ads_Express);
            //Debug.LogError(ads_num);
            if (ads_num > 0)
            {
                this._Btn_Free_Power.enabled = false;
                this.Text_Free.text = ads_num.ToString();
                if (timeSeq > 0)
                    TimerManager.Instance.RemoveTimer(timeSeq);
                timeSeq = TimerManager.Instance.AddTimer(1000, ads_num, AdsCountDown);
            }
            else
            {
                this.Text_Free.text = "免费能量";
                this._Btn_Free_Power.enabled = true;
            }
        }
        else
        {
            this._Btn_Free_Power.gameObject.SetActive(false);
        }

        if (!AdsManager.Instance.AdsReady(AdsNameConst.Ads_Express))
        {
            this._Btn_Free_Power.gameObject.SetActive(false);
        }
#if UNITY_IOS
        if (!AdsManager.Instance.AdsReady(AdsNameConst.Ads_Express) || AdsManager.Instance.AdsCoolTime(AdsNameConst.Ads_Express) > 0)
        {
            this._Btn_Free_Power.gameObject.SetActive(false);
        }
#endif

        //this._Btn_Free_Power.gameObject.SetActive(AdsManager.Instance.AdsReady(AdsNameConst.Ads_Express));
    }

    private void AdsCountDown(int seq)
    {
        ads_num--;
        this.Text_Free.text = ads_num.ToString();
        if (ads_num <= 0)
        {
            this.Text_Free.text = "免费能量";
            this._Btn_Free_Power.enabled = true;
        }
    }
#endregion

    protected override void OnRefresh()
    {
        base.OnRefresh();

        _isTravelPhotoReady = false;

        //回复到默认旋转
        earth = ExpressController.Instance.Earth.GetComponent<EarthMono>();
        earth.OnTravel = false;

        if (ExpressDataManager.Instance.ExpSetting != null)
        {
            ExpressSetting expSetting = ExpressDataManager.Instance.ExpSetting;

            _text_state = _Btn_start.transform.Find("Text_State").GetComponent<Text>();
            _trans_textRemove = _Btn_start.transform.Find("Text_Remove_t");

            string timebonus = expSetting._time_bonus;
            Debug.Log("timebonus " + timebonus + "enegy: " + expSetting._energy);
            if (expSetting._energy <= 0)
            {
                if (expSetting._time_bonus == "0")
                {
                    ExpressDataManager.Instance.InitServerData(() =>
                    {
                        Debug.Log("刷新成功");
                        timebonus = expSetting._time_bonus;
                        OnRefresh();

                    }, OnInitFromServerFailed);
                }
                else
                {
                    OpenCountDownTimerUI(timebonus);
                }

            }
            else
            {
                OpenPowerUI();
            }
        }

        ReflashAds(AdsNameConst.Ads_Express.Name);
    }

    private void BuyPower(uint enegy_id, Action<int> enegyCallback)
    {
        if (dict.ContainsKey(enegy_id))
        {
            m_currentInfo = dict[enegy_id];
            PayManager.Instance.Pay((int)enegy_id, (id, suc) =>
            {
                if (id == enegy_id && suc)
                {
                    if (m_currentInfo.type == 4)
                    {
                        //购买成功
                        if (enegyCallback != null)
                        {
                            enegyCallback(dict[enegy_id].scene_int);
                        }
                    }
                }
                //else
                //{
                //    //购买失败
                //    NoticeManager.Instance.ShowTip("购买失败！请重试！");
                //}
            });
        }
        else
        {
            Debug.Log("不存在这个id: " + enegy_id);
        }
    }

    public void StartTravel()
    {
        if (_isOnGoumai)
        {
            BuyPower();
        }
        else
        {
            int enegy = ExpressDataManager.Instance.ExpSetting._energy;
            if (enegy >= ExpressConsts.powerCost_perTravel)
            {
                _Panel_block.SetActive(true);
                OnTravel();
            }
            else
            {
                BuyPower();
            }
        }
    }

    private void OnTravel()
    {
        //ui滑出
        ExpressController.Instance.GetUIAnimatorEx(WinNames.StartPanel).CrossFade(eExpressUIAnimState.StartPaneOut.ToString(), ExpressConsts.dur_crossfade_closeUI);


        //地球模型向后方移动
        earth = ExpressController.Instance.Earth.GetComponent<EarthMono>();
        earth.FarwawyFromCam();
        earth.OnTravel = true;

        AudioClip clip = ExpressResManager.GetAudioClip(ExpressConsts.audio_earth_rotate);
        AudioManager.Instance.PlaySound(clip);

        TimerManager.Instance.AddTimer(ExpressConsts.dur_earth_move, () =>
        {
            TimerManager.Instance.AddTimer(ExpressConsts.dur_earth_rotate, () =>
            {

                earth.CancelTravel();
                earth.OpenEarthArkitectureAnimate();

                //开始弧形动画
                Transform dotweenTrans = ExpressPara.GetDoTweenPath("0").transform;
                Transform lediTrans = ExpressController.Instance.LediAnimator.transform;

                lediTrans.SetParent(dotweenTrans);
                lediTrans.ResetTransformForLocal();

                ExpressController.Instance.LediAnimator.CrossFade("fly_at", 0f);

                DOTweenPath d_path = ExpressPara.GetDoTweenPath("0");
                d_path.DORestart();

                //等待乐迪飞行动画播完
                TimerManager.Instance.AddTimer(ExpressConsts.dur_actor_ledifly, () => { _isFlayAnimateFinished = true; });

                _isTravelStart = true;
                _isFlayAnimateFinished = false;

                ExpressDataManager.Instance.StartTravel((netInfo) =>
                {
                    //第一次获取照片时，会显示手型
                    //if (!PlayerPrefs.HasKey(ExpressConsts.key_first_photo))
                    //{
                    //    _HandTip.SetActive(true);
                    //    PlayerPrefs.SetInt(ExpressConsts.key_first_photo, 1);
                    //}
                    Debug.Log("TravelFinished____________________________");
                    ExpressDataManager.Instance.InsertGalaryPhoto(netInfo);
                    //已经从服务器得到了旅行的图片数据，说明服务端旅行逻辑成功执行，需要移除能量点
                    ExpressDataManager.Instance.RemovePower(ExpressConsts.powerCost_perTravel);

                }, (traveldat) =>
                {

                    loadreturnArg = traveldat;
                    _isTravelPhotoReady = true;
                    _Panel_block.SetActive(false);

                }, OnImageLocalloadError);


            });


        });
    }

    private void BuyPower()
    {
        BuyPower(ExpressConsts.pay1id, (powbuy) =>
        {
            ExpressDataManager.Instance.AddPower(powbuy);
            WindowManager.Instance.OpenWindow(WinNames.StartPanel);
        });
        ExpressController.Instance.GetUIAnimatorEx(WinNames.StartPanel).CrossFade(eExpressUIAnimState.StartPanelIn.ToString(), ExpressConsts.dur_crossfade_openUI);
    }

    //刷新照片数量UI
    private void RefreshPhotoCountUI()
    {
        _text_PhotoAmount.text = string.Format("{0}/{1}", ExpressDataManager.Instance.TotalGallayGettedCount, ExpressDataManager.Instance.TotalGallaryCount);
    }

    //重新刷新服务器数据失败了
    private void OnInitFromServerFailed()
    {
        _text_PowerNum.text = string.Format("你有{0}个", ExpressDataManager.Instance.ExpSetting._energy);

        _Panel_powerRemain.SetActive(true);
        _Panel_timer.gameObject.SetActive(false);

        _text_state.text = "购买";
        _trans_textRemove.SetActive(false);
        _isOnGoumai = true;
    }

    //顶部能量ui
    private void OpenPowerUI()
    {
        _text_PowerNum.text = string.Format("你有{0}个", ExpressDataManager.Instance.ExpSetting._energy);

        _Panel_powerRemain.SetActive(true);
        _Panel_timer.gameObject.SetActive(false);

        _text_state.text = "出发";
        _trans_textRemove.SetActive(true);
        _isOnGoumai = false;

        RefreshPhotoCountUI();
    }

    //顶部倒计时ui
    private void OpenCountDownTimerUI(string timebonus)
    {
        _Panel_timer.ReStartTimer();
        long lastTimerStartTime = long.Parse(timebonus);
        long currentTime = TimeUtils.CurUnixTime;
        int timeToLastTimerStartTime = (int)(currentTime - lastTimerStartTime);
        if (timeToLastTimerStartTime > 0)
        {
            int timerTime = CountdownWithReset - timeToLastTimerStartTime;
            if (timerTime > 0)
            {//存档记录有倒计时，现在还没过过倒计时的时长，继续开始倒计时
             //开启倒计时
                _Panel_timer.m_totalTime = timerTime;
                _Panel_powerRemain.SetActive(false);
                _Panel_timer.gameObject.SetActive(true);
            }
            else
            {
                Debug.LogError("倒计时参数错误，倒计时时长超过24h");
            }

        }
        else
        {
            Debug.LogError("倒计时参数错误");
        }

        _text_state.text = "购买";
        _trans_textRemove.SetActive(false);
        _isOnGoumai = true;

        RefreshPhotoCountUI();
    }

    protected override void OnUpdate()
    {
        base.OnUpdate();

        if (Input.GetKeyDown(KeyCode.G))
        {
            OnTravel();
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
           GallaryPanel.m_current_ui_startposition = UGUITweener.GetCanvasLocalPos(WindowManager.Instance.canvas, _Btn_Free_Power.GetComponent<RectTransform>());
            ExpressImageLocalLoadRuturnArg l = new ExpressImageLocalLoadRuturnArg(null, 503005020, "法国");
            WindowManager.Instance.OpenWindow(WinNames.PhotoShowPanel, l);
        }

        if (Input.GetKeyDown(KeyCode.Y))
        {
            ExpressDataManager.Instance.ExpSetting._energy = 1;
            ExpressDataManager.Instance.ExpSetting._time_bonus = "0";
            OnRefresh();
        }

        if (Input.GetKeyDown(KeyCode.Z))
        {
            Debug.Log("删除本地存档");
            PlayerPrefs.DeleteKey("key_gallary_localdata");
        }

        if (Input.GetKeyDown(KeyCode.A))
        {
            Cmd.PhotoInfo netinfo = new Cmd.PhotoInfo();
            uint v = (uint)UnityEngine.Random.Range(503006000, 503006022);
            netinfo.photo_id = v.ToString();
            netinfo.area_type = (int)ExpressDataManager.Instance.TotalGallayInfoDic[v]._continent;
            netinfo.photo_url = ExpressDataManager.Instance.TotalGallayInfoDic[v]._url;
            netinfo.title = ExpressDataManager.Instance.TotalGallayInfoDic[v]._imagename;
            ExpressDataManager.Instance.InsertGalaryPhoto(netinfo);
        }

        if (_isTravelStart)
        {
            _travelTimer += Time.deltaTime;
            if ((_travelTimer > ExpressConsts.timeout_showPhoto || _isTravelPhotoReady) && _isFlayAnimateFinished)
            {
                _travelTimer = 0;
                _isTravelStart = false;
                _isTravelPhotoReady = false;

                if (loadreturnArg != null)
                {
                    Debug.Log("Open PhotoShow_____"); 
                    WindowManager.Instance.OpenWindow(WinNames.PhotoShowPanel,EWindowLayerEnum.PopupLayer, loadreturnArg);
                    WindowManager.Instance.OpenWindow(WinNames.GallaryPanel);
                }


                earth.ResetEarthArkitecture();
                earth.CloseToCam();
            }


        }


    }

#region UIEvent

    private void OnGallayBtnClicked()
    {
        //HideHandTip();
        WindowManager.Instance.OpenWindow(WinNames.GallaryPanel);
        ExpressDataManager.Instance.TotalGallayInfo.lastNewaddPicture = ExpressConsts.defaultUID;
    }

    private ExpressImageLocalLoadRuturnArg loadreturnArg;
    private void OnStartClicked()
    {
        StartTravel();
    }

    private void OnImageLocalloadError()
    {
        Debug.Log("网络连接失败");
        loadreturnArg = null;
        _isTravelPhotoReady = true;
        _Panel_block.SetActive(false);
        earth.CancelTravel();
        NoticeManager.Instance.ShowTip("网络连接失败！");
        ExpressController.Instance.GetUIAnimatorEx(WinNames.StartPanel).CrossFade(eExpressUIAnimState.StartPanelIn.ToString(), ExpressConsts.dur_crossfade_openUI);
    }

    private void OnFreePowerBtnClicked()
    {
        if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_Express))
        {
            AdsManager.Instance.ShowAds(AdsNameConst.Ads_Express, false);
        }
        else
        {
            Debug.Log("广告还未准备好");
        }
    }


    //private void HideHandTip()
    //{
    //    if (_HandTip.gameObject.activeInHierarchy) _HandTip.SetActive(false);
    //}

    private void OnPowerShowPanelBtnClicked()
    {
        BuyPower();
    }

    private void OnBackBtnClicked()
    {
        WindowManager.Instance.CloseWindow(WinNames.StartPanel);
        //HideHandTip();
        GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
    }

#endregion

}
